import {ElMessageBox} from 'element-plus'

/**
 * 确认对话框
 * @param {string} message 提示信息
 * @param {Function} callback 确认回调
 * @param {string} title 标题
 * @param {string} type 类型：success/info/warning/error
 */
export function confirm(message, callback, title = '提示', type = 'warning') {
    ElMessageBox.confirm(message, title,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type
        }
    ).then(() => {
        callback && callback()
    }).catch(() => {
    })
}

/**
 * 输入对话框
 * @param {string} message 提示信息
 * @param {Function} callback 确认回调
 * @param {string} title 标题
 * @param {string} inputPattern 输入验证正则
 * @param {string} inputErrorMessage 输入错误提示
 */
export function input(
    message,
    callback,
    title = '提示',
    inputPattern = null,
    inputErrorMessage = '输入格式不正确'
) {
    ElMessageBox.prompt(message, title,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPattern,
            inputErrorMessage
        }
    ).then(({value}) => {
        callback && callback(value)
    }).catch(() => {
    })
}

export const getEnumLabel = (options, value) => {
    const option = options?.find(opt => opt.value === value)
    return option ? option.label : value
}

export const getTagType = (options, value) => {
    const option = options?.find(opt => opt.value === value)
    return option?.type || 'primary'
}

export const formatValue = (value) => {
    return value === undefined || value === null ? '-' : value;
}

/**
 * 在数组中插入对象到指定对象后面
 * @param {Array} array - 原始数组
 * @param {Object} newObject - 要插入的新对象
 * @param {Function} predicate - 用于查找指定对象的谓词函数
 */
export function insertAfter(array, newObject, predicate) {
    const targetIndex = array.findIndex(predicate);
    if (targetIndex !== -1) {
        array.splice(targetIndex + 1, 0, newObject);
    }
}

export function clearDefaultField(object) {
    for (const key in object) {
        if (object.hasOwnProperty(key)) {
            const value = object[key];
            if (value === '' || value === null || value === undefined) {
                delete object[key];
            }
        }
    }
}

export const hashCode = (str) => {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        hash = (hash << 5) - hash + str.charCodeAt(i);
        hash |= 0; // 转换为32位整数
    }
    return hash;
};

export function getRandomColor(str) {
    let hash = 1315423911, i, ch;
    for (i = str.length - 1; i >= 0; i--) {
        ch = str.charCodeAt(i);
        hash ^= ((hash << 5) + ch + (hash >> 2));
    }
    return "#" + (hash & 0x7FFFFFFF).toString(16).substr(0, 6)
}